/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import CRUD.MemberHome;
import Utility.Utility;
import beans.RegisterBeanForum;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.SQLData;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import xmlMapping.Member;
import xmlMapping.Theme;

/**
 *
 * @author labib
 */
public class SignUp extends org.apache.struts.actions.DispatchAction {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward register(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        /// we must check for registertaion flage 

        try {
            RegisterBeanForum register = (RegisterBeanForum) form;
            Member newmember = new Member();

            ActionErrors errors = new ActionErrors();

            String Username = register.getUserName();
            Member testfind = new MemberHome().findByUserName(Username);
            if (register.getPassword().length() < 6) {
                errors.add("password", new ActionMessage("Password"));

                saveErrors(request, errors);

                return mapping.findForward("error");

            }
            String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6LdNesQSAAAAAEXUT7A-rvpKCtdLTqZVEoSuDx8d");

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (reCaptchaResponse.isValid()) {
         
        } else {
         errors.add("invalidCap", new ActionMessage("InvalidCaption"));


                saveErrors(request, errors);

                return mapping.findForward("error");
        }
            if (testfind != null) {
                System.out.println(" member not null " + testfind.getFname());
                errors.add("userName", new ActionMessage("UserNameError"));


                saveErrors(request, errors);

                return mapping.findForward("error");

            } else {











                Utility ut = new Utility();
                String encrypted = ut.encrypt(register.getPassword());
                newmember.setUserName(register.getUserName());
                newmember.setPassword(encrypted);
                newmember.setEmail(register.getEmail());
                newmember.setLname(register.getLastName());
                newmember.setFname(register.getFirstName());
                newmember.setStreet(register.getStreet());
                newmember.setCity(register.getCity());
                newmember.setCountry(register.getCountry());
                Theme th = new Theme();
                th.setThemeId(1);
                newmember.setTheme(th);
                newmember.setType("mem");

                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

                try {
                    Date dd = sdf.parse(register.getBirthday());
                    System.out.println(" dd " + dd.toString());
//          
                      newmember.setBirthday(dd);
                } catch (Exception c) {
                    c.printStackTrace();
                }






                newmember.setPhoto("images/" + register.getImg().getFileName());
                MemberHome hom = new MemberHome();
                FormFile formFile = register.getImg();
                hom.persist(newmember);
                if (formFile.equals(null) || formFile.getFileName().equals("")) {
                    System.out.println(" file image is empty ");
                } else {
                    FileOutputStream outputStream = null;

                    String path = getServlet().getServletContext().getRealPath("") + "/" + "images/"
                            + formFile.getFileName();
                    outputStream = new FileOutputStream(new File(path));
                    outputStream.write(formFile.getFileData());
                    outputStream.close();
                }
            }
        } catch (Exception x) {
            return mapping.findForward("error");
        }
        return mapping.findForward("registerok");
    }

    public ActionForward Change(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        /// we must check for registertaion flage 

        System.out.println(" changing data ");
        RegisterBeanForum register = (RegisterBeanForum) form;
        MemberHome hom = new MemberHome();
        Member newmember = hom.findById( (Integer)request.getSession().getAttribute("id"));
        ActionErrors errors = new ActionErrors();
        errors.add("userName", new ActionMessage("UserNameError"));

        if (register.getPassword() == null || register.getPassword().length() < 6) {
            errors.add("password", new ActionMessage("Password"));
            saveErrors(request, errors);
            return mapping.findForward("editError");
        }















        newmember.setUserName(register.getUserName());


        Utility ut = new Utility();
        String encrypted = ut.encrypt(register.getPassword());

        newmember.setPassword(encrypted);



        newmember.setEmail(register.getEmail());
        newmember.setLname(register.getLastName());
        newmember.setFname(register.getFirstName());
        newmember.setStreet(register.getStreet());
        newmember.setCity(register.getCity());
        newmember.setCountry(register.getCountry());
        Theme th = new Theme();
        th.setThemeId(1);
        newmember.setTheme(th);
        newmember.setType(newmember.getType());
        newmember.setPhoto("images/" + register.getImg().getFileName());
      
                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

                try {
                    Date dd = sdf.parse(register.getBirthday());
                    System.out.println(" dd " + dd.toString());
//          
                      newmember.setBirthday(dd);
                } catch (Exception c) {
                    c.printStackTrace();
                }



        FormFile formFile = register.getImg();
        hom.attachDirty(newmember);
        if (formFile.equals(null) || formFile.getFileName().equals("")) {
            System.out.println(" file image is empty ");
        } else {
            FileOutputStream outputStream = null;

            String path = getServlet().getServletContext().getRealPath("") + "/" + "images/"
                    + formFile.getFileName();
            outputStream = new FileOutputStream(new File(path));
            outputStream.write(formFile.getFileData());
            outputStream.close();
        }
        return mapping.findForward("registerok");
    }
}
